

if("`c(os)'"=="Windows"){
	local tableSaveDir = "Tables\"
	local plotSaveDir = "Plots\NeighborAnalysis\"
	local pythonSaveDir = "PythonScripts\"
}
else{
	local tableSaveDir = "Tables/"
	local plotSaveDir = "Plots/NeighborAnalysis/"
	local pythonSaveDir = "PythonScripts/"
}


//Execute python script to find the appropriate changes in treated neighbor states and add variable "delNeighborNoSafety"
python script "`pythonSaveDir'addNeighboringStateVariables.py"

//Establish Control Variable Sets
local Spec1Controls = "c.normYear#i.stateGroup c.quadYear#i.stateGroup asinhMetroPop asinhNonMetroPop asinhMetroInc asinhNonMetroInc logrealmeangasprice logemployment loglicenseddrivers logrealstategdp logroadmileage"
local Spec2Controls = "`Spec1Controls'"
local Spec3Controls = "`Spec2Controls' i.vmtDummyExtSpec3"
local Spec4Controls = "`Spec2Controls' i.vmtDummyExtSpec4"

//Establish Cluster Variable
local clusterVar = "stateGroup year"

//Absorb Vars are always time and state fixed effects
local absorbVars = "ib51.stateGroup ib1995.year"

//Event Study Table format
local fmtEventStudy = `"cells(b(fmt(3) star) se(par fmt(3))) keep(*neighborDummy*  *shiftedBoundRelYear*) nocon label compress longtable mtitles("\makecell{No \\ DSCs}" "\makecell{Documented \\ DSCs}" "\makecell{Suspected \\ DSCs}" "\makecell{Potential \\ DSCs}") starlevels(* 0.1 ** 0.05 *** 0.01) addnotes("* p \textless 0.1, ** p \textless 0.05, *** p \textless 0.01" "Note: All models include state and year fixed effects as well as state-level time trends." "All models cluster standard errors  by state.")"'



//Add Dummy Variables for Spec2 state Event Study
//Define +- bounds for event study
local bound = 6
//Define Bounds
local lowerBound = -`bound'
local upperBound = `bound'

//Define the relative time period that we will use
local relYear = -1

//Determine the dummy index of the relative year
local relIndex = 1-`lowerBound'+`relYear'

//Generate New Variable
gen boundRelYear = yearrelativeend
//Enforce Bounds
replace boundRelYear = `lowerBound' if boundRelYear<=`lowerBound'
replace boundRelYear = `upperBound' if boundRelYear>=`upperBound'
replace boundRelYear = . if yearrelativeend==.

replace boundRelYear = -1 if boundRelYear==.
qui tab boundRelYear, gen(boundRelYear)
replace boundRelYear = . if yearrelativeend==.

//For plotting purposes
gen tempx = 5
gen tempx1 = 4.85
gen tempx2 = 5.15
gen tempy = 0

//Create shifted Bounds for the other events (neighboring states changing their policy)
gen shiftedBoundRelYear = boundRelYear - `lowerBound'+1
replace shiftedBoundRelYear = `relIndex' if boundRelYear==.

qui levelsof delNeighborNoSafety
foreach numNeighborState in `r(levels)'{
	if(`numNeighborState'>0){
		qui gen shiftedBoundRelYear`numNeighborState' = `relYear'
		qui levelsof statecode if delNeighborNoSafety==`numNeighborState'
		di "`numNeighborState'"
		foreach tempSC in `r(levels)'{
			qui sum year if statecode=="`tempSC'" & delNeighborNoSafety==`numNeighborState'
			qui replace shiftedBoundRelYear`numNeighborState' = year-`r(min)' if statecode=="`tempSC'"
			qui replace shiftedBoundRelYear`numNeighborState' = `lowerBound' if shiftedBoundRelYear`numNeighborState'<`lowerBound' & statecode=="`tempSC'"
			qui replace shiftedBoundRelYear`numNeighborState' = `upperBound' if shiftedBoundRelYear`numNeighborState'>`upperBound' & statecode=="`tempSC'" 
			qui replace shiftedBoundRelYear`numNeighborState' = shiftedBoundRelYear`numNeighborState' +`bound'+1 if statecode=="`tempSC'"
		}
		qui replace shiftedBoundRelYear`numNeighborState' = `relIndex' if shiftedBoundRelYear`numNeighborState'==`relYear'
	}
}

xtset stateGroup year
gen diffDelNeighborNoSafety = d.delNeighborNoSafety

levelsof statecode if diffDelNeighborNoSafety==2

foreach tempSC in `r(levels)'{
	sum delNeighborNoSafety if statecode=="`tempSC'" & diffDelNeighborNoSafety==2
	local indFromCopy = `r(mean)'
	local indToCopy = `indFromCopy'-1
	replace shiftedBoundRelYear`indToCopy' = shiftedBoundRelYear`indFromCopy' if statecode=="`tempSC'"
}


local finIndex = `upperBound'-`lowerBound'+1
forvalues ind = 1(1)`finIndex'{
	di "`ind'"
	gen neighborDummy`ind' = 0
	
	
	qui sum delNeighborNoSafety
	local numInd = `r(max)'
	
	qui levelsof statecode
	foreach tempSC in `r(levels)'{
		forvalues nInd = 1(1)`numInd'{
			qui sum delNeighborNoSafety if statecode=="`tempSC'"
			if(`nInd'<=`r(max)'){
				qui replace neighborDummy`ind'=neighborDummy`ind'+1 if shiftedBoundRelYear`nInd'==`ind' & statecode=="`tempSC'"
			}
		}
	}
	local trueT = `ind'-`bound'-1
	
	if(`trueT'==`upperBound'){
		label var neighborDummy`ind' "Neighbor Event: t $\geq$ `trueT'"
	}
	else if(`trueT'==`lowerBound'){
		label var neighborDummy`ind' "Neighbor Event: t $\leq$ `trueT'"
	}
	else{
		label var neighborDummy`ind' "Neighbor Event: t = `trueT'"
	}
	
	
}
//Define main event labels
label define shiftedBoundRelYear 1 "Main Event: t $\leq$ -6" 2 "Main Event: t=-5" 3 "Main Event: t=-4" 4 "Main Event: t=-3" 5 "Main Event: t=-2" 6 "Main Event: t=-1" 7 "Main Event: t=0" 8 "Main Event: t=1" 9 "Main Event: t=2" 10 "Main Event: t=3" 11 "Main Event: t=4" 12 "Main Event: t=5" 13 "Main Event: t $\geq$ 6"
label values shiftedBoundRelYear shiftedBoundRelYear

// drop neighborDummy`relIndex' to enforce baseline
replace neighborDummy`relIndex' = 1
drop neighborDummy`relIndex'
drop boundRelYear`relIndex'

// //Label values


// //Plot formats
// local plotFormat = `"vertical yline(0) keep(*neighborDummy*) omitted baselevels xlabel(1 "≤-6" 2 "-5" 3 "-4" 4 "-3" 5 "-2" 6 "-1" 7 "0" 8 "1" 9 "2" 10 "3" 11 "4" 12 "5" 13 "≥6", angle(0)) xtitle("Years Relative to Neighbor Removal")"'
//
// local plotFormat = `"vertical yline(0) keep(*neighborDummy*) drop(neighborDummy1 neighborDummy`finIndex') omitted baselevels xlabel(1 "-5" 2 "-4" 3 "-3" 4 "-2" 5 "-1" 6 "0" 7 "1" 8 "2" 9 "3" 10 "4" 11 "5", angle(0)) xtitle("Years Relative to Neighbor Removal") ytitle("Proportional Change in VMT")"'

local plotFormat = `"vertical yline(0) keep(*neighborDummy*) drop(neighborDummy1_res neighborDummy13_res) xtitle("Years Relative to Neighbor Removal") ytitle("Proportional Change in Travel" "relative to {&tau}=-1") xlabel(1 "-5" 2 "-4" 3 "-3" 4 "-2" 5 "-1" 6 "0" 7 "1" 8 "2" 9 "3" 10 "4" 11 "5", angle(0))"'


//Run regressions and output results

local title = "VMT Spillover Analysis Event Study Results \label{atab:VMTSpillover`upperBound'}"

local plot_order = "neighborDummy2_res neighborDummy3_res neighborDummy4_res neighborDummy5_res . neighborDummy7_res neighborDummy8_res neighborDummy9_res neighborDummy10_res neighborDummy11_res neighborDummy12_res"

local es_controls = "boundRelYear1 boundRelYear2 boundRelYear3 boundRelYear4 boundRelYear5 boundRelYear7 boundRelYear8 boundRelYear9 boundRelYear10 boundRelYear11 boundRelYear12 boundRelYear13"
local neighbor_es_controls = "neighborDummy1 neighborDummy2 neighborDummy3 neighborDummy4 neighborDummy5 neighborDummy7 neighborDummy8 neighborDummy9 neighborDummy10 neighborDummy11 neighborDummy12 neighborDummy13"
local es_plot_order = "boundRelYear2_res boundRelYear3_res boundRelYear4_res boundRelYear5_res . boundRelYear7_res boundRelYear8_res boundRelYear9_res boundRelYear10 boundRelYear11_res boundRelYear12_res"

//Neighbor Analysis
//Spec1 specification
// reghdfe logvmt ib`relIndex'.shiftedBoundRelYear neighborDummy1-neighborDummy`finIndex' `Spec1Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
regFWL logvmt, `es_controls' `neighbor_es_controls', `Spec1Controls', `absorbVars', `clusterVar', _
// coefplot, `plotFormat' title("Neighbor Event Coefficients") name("Spec1SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white))
coefplot, `plotFormat' ytitle("Proportional Change in Total Travel")  ylabel(-.05 0 .05 .1) ytick(-.05(.01).12) order(`plot_order') name("Spec1SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white)) p1(label("With Neighbor Coefficients")) addplot(scatter tempy tempx, color(navy)) color(navy) title("Neighbor Event Coefficients")
graph export "`plotSaveDir'NeighborStateSpec1VMT`upperBound'.png", replace name("Spec1SpilloverVMT`upperBound'")
eststo Spec1
// //Spec2 specification
// reghdfe logvmt ib`relIndex'.shiftedBoundRelYear neighborDummy1-neighborDummy`finIndex' `Spec2Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
regFWL logvmt, `es_controls' `neighbor_es_controls', `Spec2Controls', `absorbVars', `clusterVar', _
// coefplot, `plotFormat' title("Neighbor Event Coefficients") name("Spec2SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white))
coefplot, `plotFormat' ytitle("Proportional Change in Total Travel")  ylabel(-.05 0 .05 .1) ytick(-.05(.01).12) order(`plot_order') name("Spec2SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white)) p1(label("With Neighbor Coefficients")) addplot(scatter tempy tempx, color(navy)) color(navy) title("Neighbor Event Coefficients")
graph export "`plotSaveDir'NeighborStateSpec2VMT`upperBound'.png", replace name("Spec2SpilloverVMT`upperBound'")
eststo Spec2 
// //Spec2 specification
// reghdfe logvmt ib`relIndex'.shiftedBoundRelYear neighborDummy1-neighborDummy`finIndex' `Spec3Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
regFWL logvmt, `es_controls' `neighbor_es_controls', `Spec3Controls', `absorbVars', `clusterVar', _
// coefplot, `plotFormat' title("Neighbor Event Coefficients") name("Spec3SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white))
coefplot, `plotFormat' ytitle("Proportional Change in Total Travel")  ylabel(-.05 0 .05 .1) ytick(-.05(.01).12) order(`plot_order') name("Spec3SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white)) p1(label("With Neighbor Coefficients")) addplot(scatter tempy tempx, color(navy)) color(navy) title("Neighbor Event Coefficients")
graph export "`plotSaveDir'NeighborStateSpec3VMT`upperBound'.png", replace name("Spec3SpilloverVMT`upperBound'")
eststo Spec3
// //Spec2 specification
// reghdfe logvmt ib`relIndex'.shiftedBoundRelYear neighborDummy1-neighborDummy`finIndex' `Spec4Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
regFWL logvmt, `es_controls' `neighbor_es_controls', `Spec4Controls', `absorbVars', `clusterVar', _
// coefplot, `plotFormat' title("Neighbor Event Coefficients") name("Spec4SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white))
coefplot, `plotFormat' ytitle("Proportional Change in Total Travel")  ylabel(-.05 0 .05 .1) ytick(-.05(.01).12) order(`plot_order') name("Spec4SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white)) p1(label("With Neighbor Coefficients")) addplot(scatter tempy tempx, color(navy)) color(navy) title("Neighbor Event Coefficients")
graph export "`plotSaveDir'NeighborStateSpec4VMT`upperBound'.png", replace name("Spec4SpilloverVMT`upperBound'")
eststo Spec4


// local plotFormat = `"vertical yline(0) keep(*shiftedBoundRelYear*) omitted baselevels xlabel(1 "≤-6" 2 "-5" 3 "-4" 4 "-3" 5 "-2" 6 "-1" 7 "0" 8 "1" 9 "2" 10 "3" 11 "4" 12 "5" 13 "≥6", angle(0)) xtitle("Years Relative to Treatment Year") ytitle("Proportional Change in Total VMT")"'
//
// local plotFormat = `"vertical yline(0) keep(*shiftedBoundRelYear*) drop(1.shiftedBoundRelYear 13.shiftedBoundRelYear) omitted baselevels xlabel(1 "-5" 2 "-4" 3 "-3" 4 "-2" 5 "-1" 6 "0" 7 "1" 8 "2" 9 "3" 10 "4" 11 "5", angle(0)) xtitle("Years Relative to Inspection Removal") ytitle("Proportional Change in Total VMT")"'


local plotFormat = `"vertical yline(0) keep(*boundRelYear*) drop(boundRelYear1_res boundRelYear13_res) xtitle("Years Relative to Inspection Removal") ytitle("Proportional Change in Total Registrations" "relative to {&tau}=-1") xlabel(1 "-5" 2 "-4" 3 "-3" 4 "-2" 5 "-1" 6 "0" 7 "1" 8 "2" 9 "3" 10 "4" 11 "5", angle(0))"'
//Main Analysis Comparison
//Spec1 specification
// reghdfe logvmt ib`relIndex'.shiftedBoundRelYear `Spec1Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
regFWL logvmt, `es_controls', `Spec1Controls', `absorbVars', `clusterVar', _
eststo Spec1Main
coefplot Spec1 Spec1Main, `plotFormat' title("Main Event Coefficients") name("Spec1ComparisonVMT`upperBound'") p1(label("With Neighbor Coefficients") color(navy) ciopts(color(navy))) p2(label("Without Neighbor Coefficients") color(cranberry) ciopts(color(cranberry))) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(5) size(*.8)) order(`es_plot_order') addplot(scatter tempy tempx1, color(navy) || scatter tempy tempx2, color(cranberry)) 
graph export "`plotSaveDir'NeighborStateMainComparisonSpec1VMT`upperBound'.png", replace name("Spec1ComparisonVMT`upperBound'")
// //Spec2 specification
// reghdfe logvmt ib`relIndex'.shiftedBoundRelYear  `Spec2Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
regFWL logvmt, `es_controls', `Spec2Controls', `absorbVars', `clusterVar', _
eststo Spec2Main
coefplot Spec2 Spec2Main, `plotFormat' title("Main Event Coefficients") name("Spec2ComparisonVMT`upperBound'") p1(label("With Neighbor Coefficients") color(navy) ciopts(color(navy))) p2(label("Without Neighbor Coefficients") color(cranberry) ciopts(color(cranberry))) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(5) size(*.8)) order(`es_plot_order') addplot(scatter tempy tempx1, color(navy) || scatter tempy tempx2, color(cranberry)) 
graph export "`plotSaveDir'NeighborStateMainComparisonSpec2VMT`upperBound'.png", replace name("Spec2ComparisonVMT`upperBound'")

// //Spec2 specification
// reghdfe logvmt ib`relIndex'.shiftedBoundRelYear  `Spec3Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
regFWL logvmt, `es_controls', `Spec3Controls', `absorbVars', `clusterVar', _
eststo Spec3Main
coefplot Spec3 Spec3Main, `plotFormat' title("Main Event Coefficients") name("Spec3ComparisonVMT`upperBound'") p1(label("With Neighbor Coefficients") color(navy) ciopts(color(navy))) p2(label("Without Neighbor Coefficients") color(cranberry) ciopts(color(cranberry))) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(5) size(*.8)) order(`es_plot_order') addplot(scatter tempy tempx1, color(navy) || scatter tempy tempx2, color(cranberry)) 
graph export "`plotSaveDir'NeighborStateMainComparisonSpec3VMT`upperBound'.png", replace name("Spec3ComparisonVMT`upperBound'")

// //Spec2 specification
// reghdfe logvmt ib`relIndex'.shiftedBoundRelYear  `Spec4Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
regFWL logvmt, `es_controls', `Spec4Controls', `absorbVars', `clusterVar', _
eststo Spec4Main
coefplot Spec4 Spec4Main, `plotFormat' title("Main Event Coefficients") name("Spec4ComparisonVMT`upperBound'") p1(label("With Neighbor Coefficients") color(navy) ciopts(color(navy))) p2(label("Without Neighbor Coefficients") color(cranberry) ciopts(color(cranberry))) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(5) size(*.8)) order(`es_plot_order') addplot(scatter tempy tempx1, color(navy) || scatter tempy tempx2, color(cranberry)) 
graph export "`plotSaveDir'NeighborStateMainComparisonSpec4VMT`upperBound'.png", replace name("Spec4ComparisonVMT`upperBound'")
//
//
graph combine Spec1ComparisonVMT`upperBound' Spec1SpilloverVMT`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white)) // title("No DSCs Spec.")
graph export "`plotSaveDir'NeighborStateJointSpec1VMT`upperBound'.png", replace
graph combine Spec2ComparisonVMT`upperBound' Spec2SpilloverVMT`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white)) // title("Documented DSCs Spec.")
graph export "`plotSaveDir'NeighborStateJointSpec2VMT`upperBound'.png", replace
graph combine Spec3ComparisonVMT`upperBound' Spec3SpilloverVMT`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white)) // title("Suspected DSCs Spec.")
graph export "`plotSaveDir'NeighborStateJointSpec3VMT`upperBound'.png", replace
graph combine Spec4ComparisonVMT`upperBound' Spec4SpilloverVMT`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white)) // title("Potential DSCs Spec.")
graph export "`plotSaveDir'NeighborStateJointSpec4VMT`upperBound'.png", replace
//
// if("`c(os)'"=="Windows"){
// 	local tableSaveDir = "Tables\Spillover\"
// 	local plotSaveDir = "Plots\NeighborAnalysis\"
// 	local pythonSaveDir = "PythonScripts\"
// }
// else{
// 	local tableSaveDir = "Tables/Spillover/"
// 	local plotSaveDir = "Plots/NeighborAnalysis/"
// 	local pythonSaveDir = "PythonScripts/"
// }
//
// //Output table
// local saveFile = "`tableSaveDir'"+"NeighborAnalysisVMT`upperBound'.tex"
//
// esttab Spec1 Spec2 Spec3 Spec4 using "`saveFile'", `fmtEventStudy' title(`title') replace

drop tempx tempy tempx1 tempx2
